package com.yc.ssq.servlet;

import com.google.gson.Gson;
import com.ly.common.bean.Result;
import com.yc.ssq.bean.Ssq_lottery;
import com.yc.ssq.mapper.SsqMapper;
import com.yc.ssq.util.MyBatisHelper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

@WebServlet(name = "UploadServlet", value = "/upload.do")
@MultipartConfig //文件上传的注解配置
public class UploadServlet extends HttpServlet {

    private SsqBiz biz = new SsqBiz();

    // 405错误 响应方法有问题
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        // 接收上传的文件
        Part datafile = request.getPart("datafile");
        // 获取文件名
        String filename = datafile.getSubmittedFileName();
        // 保存文件
        datafile.write("C:\\Users\\念流年/" + filename);

//        try(FileReader fr = new FileReader("C:\\Users\\念流年/" + filename);
//            BufferedReader br = new BufferedReader(fr);
//        ){
//            // 解析文件
//            String line;
//            while ((line = br.readLine()) != null) {
//                String[] items = line.split("\\s+");
////                String sql = "insert into ssq_lottery values(" +
////                        "default,?,?,?,?,?,?,?,?,?,?,?,?)";
////                // 保存到数据库
////                DBHelper.update(sql, items);
//                SqlSession session = MyBatisHelper.getsSession();
//                Ssq_lottery ssq = new Ssq_lottery();
//                SsqMapper mapper = session.getMapper(SsqMapper.class);
//                mapper.insert(items);
//            }
//        }

        // 保存数据
        biz.save("C:\\Users\\念流年/" + filename);
        Result result = new Result(1,"文件上传成功！",null);
        // 设置响应类型
        response.setContentType("application/json;charset=utf-8");
        // 将java对象转成json字符串
        String json = new Gson().toJson(result);
        // 向浏览器输出
        response.getWriter().print(json);
    }
}
